package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisByDayMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.domain.AnalysisByDay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author げっしょく
 * @date 2021/11/5
 */
@Service
public class AnalysisByDayService {

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    @Autowired
    private LogMapper logMapper;


    public void analysis() throws ParseException {
        //获得当天时间
        String dayTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //查询昨日时间
        String yesterDay = DateUtil.yesterday().toString("yyyy-MM-dd");
        //通过当天时间查询当日注册人数
        Integer enrollment = logMapper.getEnrollment(dayTime);
        //查询当天活跃人数
        Integer active = logMapper.getActiveCount(dayTime);
        //查询当日登陆人数
        Integer loginCount = logMapper.getloginCount(dayTime);
        //查询昨日留存人数
        Integer keepCount = logMapper.getKeepCount(dayTime, yesterDay);

        QueryWrapper qw = new QueryWrapper();
        Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(dayTime);
        qw.eq("record_date", parse);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(qw);
        if (analysisByDay != null) {
            analysisByDay.setRecordDate(new SimpleDateFormat("yyyy-MM-dd").parse(dayTime));
            analysisByDay.setNumRegistered(enrollment);
            analysisByDay.setNumActive(active);
            analysisByDay.setNumLogin(loginCount);
            analysisByDay.setNumRetention1d(keepCount);
            analysisByDay.setUpdated(new Date());
            analysisByDayMapper.updateById(analysisByDay);
        }else{
            AnalysisByDay analysisByDay1 = new AnalysisByDay();
            analysisByDay1.setRecordDate(new SimpleDateFormat("yyyy-MM-dd").parse(dayTime));
            analysisByDay1.setNumRegistered(enrollment);
            analysisByDay1.setNumActive(active);
            analysisByDay1.setNumLogin(loginCount);
            analysisByDay1.setNumRetention1d(keepCount);
            analysisByDay1.setCreated(new Date());
            analysisByDay1.setUpdated(new Date());
            analysisByDayMapper.insert(analysisByDay1);
        }
    }
}
